package com.joke.mydiary.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.joke.mydiary.R;
import com.joke.mydiary.pojo.Diary;
import com.joke.mydiary.utils.BitmapUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;


public class UpdateDiaryFragment extends Fragment implements View.OnClickListener {

    public static final int HANDELFINISH = 0x1;
    public static final int PHOTO_CODE = 0x99;
    private static final int IMAGE_CODE = 0x100;
    private TextView txtUpdateDate;
    private ImageView imgUpdate;
    private EditText txtUpdateContent;
    private Button btnUpdateImage, btnUpdatePhoto, btnUpdateSave;
    private UpdateDiaryFragmentListener mListener;
    private Diary diary;
    private File photoFile;
    private MyHandel myHandel;

    public static UpdateDiaryFragment getInstance(Bundle args) {
        UpdateDiaryFragment udf = new UpdateDiaryFragment();
        udf.setArguments(args);
        return udf;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_update_diary, container, false);
        Bundle args = this.getArguments();
        diary = (Diary) args.getSerializable("diary");
        txtUpdateContent = (EditText) view.findViewById(R.id.txtUpdateContent);
        txtUpdateDate = (TextView) view.findViewById(R.id.txtUpdateDate);
        btnUpdateImage = (Button) view.findViewById(R.id.btnUpdateImage);
        btnUpdatePhoto = (Button) view.findViewById(R.id.btnUpdatePhoto);
        btnUpdateSave = (Button) view.findViewById(R.id.btnUpdateSave);
        imgUpdate = (ImageView) view.findViewById(R.id.imgUpdate);
        if (diary.getImagePath() != null && !"".equals(diary.getImagePath().trim())) {
            Bitmap bitmap = BitmapFactory.decodeFile(diary.getImagePath());
            imgUpdate.setImageBitmap(bitmap);
            imgUpdate.setAdjustViewBounds(true);
        }

        myHandel = new MyHandel(this);

        txtUpdateDate.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(diary.getDate()));
        txtUpdateContent.setText(diary.getContent());
        btnUpdateImage.setOnClickListener(this);
        btnUpdatePhoto.setOnClickListener(this);
        btnUpdateSave.setOnClickListener(this);

        return view;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (UpdateDiaryFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnUpdateSave:
                update();
                boolean falg = mListener.update(diary);
                if (falg) {
                    mListener.showDiaryFragment(diary);
                }
                break;
            case R.id.btnUpdateImage:
                chooseImage();
                break;
            case R.id.btnUpdatePhoto:
                takePhoto();
                break;
        }

    }

    private void update() {
        if (!TextUtils.isEmpty(txtUpdateContent.getText())) {
            diary.setContent(txtUpdateContent.getText().toString());
            if (photoFile != null) {
                diary.setImagePath(photoFile.getPath());
            }
        } else {
            Toast.makeText((Context) mListener, "修改内容不能为空！", Toast.LENGTH_SHORT).show();
        }
    }

    //处理Intent返回结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == PHOTO_CODE) {
                Bitmap bm =  BitmapUtils.decodeSimpledBitmapFromResourse(photoFile.getPath(), 400, 400);
                imgUpdate.setImageBitmap(bm);
                imgUpdate.setAdjustViewBounds(true);
            } else if (requestCode == IMAGE_CODE) {
                Uri uri = data.getData();
                InputStream in = mListener.getInputStreamByUrl(uri);
                if (in != null) {
                    photoFile = getOutputMediaFile(in);
                    Bitmap bm = BitmapUtils.decodeSimpledBitmapFromResourse(photoFile.getPath(), 400, 400);
                    imgUpdate.setImageBitmap(bm);
                    imgUpdate.setAdjustViewBounds(true);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //用户选择图片后通过InputStream备份一个图片
    public File getOutputMediaFile(InputStream in) {
        String fileName = System.currentTimeMillis() + ".jpg";
        String rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
        File mediaFile = new File(rootPath + File.separator + fileName);
        int len = 0;
        byte[] buf = new byte[1024];
        BufferedOutputStream bufOut;
        try {
            bufOut = new BufferedOutputStream(new FileOutputStream(mediaFile));
            while ((len = in.read(buf)) != -1) {
                bufOut.write(buf, 0, len);
                bufOut.flush();
            }
            bufOut.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mediaFile;
    }

    //选择图片
    public void chooseImage() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_CODE);
    }

    //启动系统相机
    public void takePhoto() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFileUri());
        startActivityForResult(intent, PHOTO_CODE);
    }

    //取得拍照完毕的照片的uri
    private Uri getOutputMediaFileUri() {
        photoFile = getOutputMeidaFile();
        return Uri.fromFile(photoFile);
    }

    //用于拍照完毕后保存文件
    private File getOutputMeidaFile() {
        String fileName = System.currentTimeMillis() + ".jpg";
        String rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
        File mediaFile = new File(rootPath + File.separator + fileName);
        return mediaFile;
    }


    public interface UpdateDiaryFragmentListener {

        public boolean update(Diary diary);

        public void showDiaryFragment(Diary diary);

        public InputStream getInputStreamByUrl(Uri uri);


    }

    public class MyHandel extends Handler {
        private WeakReference<UpdateDiaryFragment> weakReference;

        public MyHandel(UpdateDiaryFragment udf) {
            this.weakReference = new WeakReference<UpdateDiaryFragment>(udf);
        }

        @Override
        public void handleMessage(Message msg) {
            UpdateDiaryFragment udf = weakReference.get();
            if (udf != null) {
                if (msg.what == HANDELFINISH) {
                    //处理消息
                    photoFile = (File) msg.obj;
                }
            }
        }
    }

}
